package com.gexiaobao.pigeon.ui.fragment.mall

import android.annotation.SuppressLint
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.model.bean.ImageModel
import com.gexiaobao.pigeon.app.model.bean.ReasonListBean
import com.gexiaobao.pigeon.app.model.param.RefundReturnParam
import com.gexiaobao.pigeon.app.rxui.tablayout.listener.GlideEngine
import com.gexiaobao.pigeon.app.util.ImgUtils
import com.gexiaobao.pigeon.app.util.PictureUtil
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.databinding.FragmentReturnOfGoodsBinding
import com.gexiaobao.pigeon.permissions.PermissionInterceptor
import com.gexiaobao.pigeon.ui.adapter.ReturnGoodsReasonAdapter
import com.gexiaobao.pigeon.ui.mall.MallViewModel
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.luck.picture.lib.basic.PictureSelectionModel
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.language.LanguageConfig
import com.luck.picture.lib.style.PictureSelectorStyle
import com.yanzhenjie.recyclerview.SwipeRecyclerView
import com.zs.easy.imgcompress.EasyImgCompress
import com.zs.easy.imgcompress.listener.OnCompressSinglePicListener
import com.zs.easy.imgcompress.util.GBMBKBUtil
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.LogUtils
import java.io.File


/**
 * @Author      : hxw
 * @Date        : 2023/7/4 9:04
 * @Describe    : 退货
 */
class FragmentReturnOfGoods : BaseFragment<MallViewModel, FragmentReturnOfGoodsBinding>() {

    private lateinit var dialogBottom: BottomSheetDialog
    private var orderId = 0
    private var mShopUserId = 0
    private var isDamage = 0//是否损坏
    private var mGoodsIds = ""
    private var mapImageId: MutableMap<Int, Int> = mutableMapOf()
    private var mRealPath: String = ""
    private val mAdapterReason: ReturnGoodsReasonAdapter by lazy { ReturnGoodsReasonAdapter(arrayListOf()) }

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.includeBar.tvWhiteTitle.text = "退货"
        orderId = requireArguments().getInt("orderId")
        mShopUserId = requireArguments().getInt("shopUserId")
        mGoodsIds = arguments?.get("goodsId").toString()
        isDamage = if (mDatabind.rbDamage.isChecked) {
            1
        } else {
            2
        }
        upLoadImageGoods()
    }


    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.ivReturnOfGoodsReason, mDatabind.tvReturnGoodsSubmit, mDatabind.includeBar.ivBack) {
            when (it) {
                mDatabind.includeBar.ivBack -> {
                    nav().navigateUp()
                }

                mDatabind.ivReturnOfGoodsReason -> {
                    showBottomDialogReason()
                }

                mDatabind.tvReturnGoodsSubmit -> {
                    requestReturnGoods()
                }
            }
        }
    }

    override fun createObserver() {
        super.createObserver()
        /** 申请退换货 */
        mViewModel.refundResult.observe(viewLifecycleOwner) {
            dismissLoading()
            if (it.isSuccess) {
                eventViewModel.toNoticeReturnGoods.value = true
                nav().navigateUp()
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
        /** 上传退货图片 */
        var index = 0
        mViewModel.evaluateImageResult.observe(viewLifecycleOwner) {
            if (it != null) {
                addNewData(mRealPath)
                mapImageId[index] = it.id
                index++
            }
        }
        /** 上传物流单号 */
        mViewModel.upLoadExpressResult.observe(viewLifecycleOwner) {
            RxToast.showToast("操作成功")
        }
    }

    private fun requestReturnGoods() {
        val sb = StringBuffer()
        mapImageId.forEach {
            sb.append(it.value.toString() + ",")
        }
        val imageId = sb.toString()
        val mImages = if (imageId.isNotEmpty()) {
            imageId.subSequence(0, imageId.length - 1).toString()
        } else {
            ""
        }
        val detailedReasons = mDatabind.etDetailedReasons.text.toString().trim()
        val reasonContent = mDatabind.tvReturnOfGoodsReason.text.toString().trim()
        if (reasonContent.isEmpty()) {
            RxToast.showToast("请选择退货理由")
            return
        }
        val body = RefundReturnParam(
            reason = reasonContent,
            detailedReasons = detailedReasons,
            damage = isDamage,//1-损坏 2-未损坏
            goodsId = mGoodsIds,
            orderId = orderId,
            shopUserId = mShopUserId,
            reviewType = 2,//1-退款 2-退货 3-换货
            type = 1,//1-小订单
            images = mImages
        )
        showLoading(getString(R.string.loading))
        mViewModel.addReturnReview(body)
    }

    @SuppressLint("MissingInflatedId", "NotifyDataSetChanged")
    private fun showBottomDialogReason() {
        val mList = ArrayList<ReasonListBean>()
        mList.add(ReasonListBean("7天无理由"))
        mList.add(ReasonListBean("商品与页面描述不符"))
        mList.add(ReasonListBean("少件/发错货/未收到货"))
        mList.add(ReasonListBean("价格变化"))
        mList.add(ReasonListBean("商品破损/包装问题"))
        mList.add(ReasonListBean("商品质量/故障"))

        dialogBottom = context?.let { BottomSheetDialog(it, R.style.BottomSheetDialog) }!!
        val dialogView: View = LayoutInflater.from(context).inflate(R.layout.bottom_return_goods_reason, null)
        val swipeRecyclerView = dialogView.findViewById<SwipeRecyclerView>(R.id.swipeRecyclerView)
        val tvReturnGoodReason = dialogView.findViewById<AppCompatTextView>(R.id.tvReturnGoodReason)
        val ivCloseBottomDialog = dialogView.findViewById<AppCompatImageView>(R.id.ivCloseBottomDialog)

        tvReturnGoodReason.isVisible = false
        swipeRecyclerView.init(LinearLayoutManager(context), mAdapterReason)
        swipeRecyclerView.adapter = mAdapterReason
        mAdapterReason.setList(mList)
        mAdapterReason.notifyDataSetChanged()
        mAdapterReason.setOnItemCheckClickListener(object : ReturnGoodsReasonAdapter.OnItemCheckClickListener {
            override fun onItemClick(position: Int) {
                mDatabind.tvReturnOfGoodsReason.text = mAdapterReason.data[position].reason
                dialogBottom.dismiss()
            }
        })
        ivCloseBottomDialog.setOnClickListener {
            dialogBottom.dismiss()
        }

        dialogBottom.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        dialogBottom.setContentView(dialogView)
        dialogBottom.show()
    }

    /** 上传图片 */
    private fun upLoadImageGoods() {
        mDatabind.uploadMultiImageView
            .setImageInfoList(null)
            // 不开启拖拽排序
            .setDrag(false)
            // 设置每行3列
            .setColumns(3)
            // 显示新增按钮
            .setShowAdd(true)
            // 设置图片缩放类型 (默认 CENTER_CROP)
            .setScaleType(ImageView.ScaleType.CENTER_CROP)
            // item点击回调
            .setImageItemClickListener { _ -> }
            // 设置删除点击监听（如果不设置，测试默认移除数据），自己处理数据删除过程
            .setDeleteClickListener { multiImageView, position ->
                context?.let {
                    AlertDialog.Builder(it)
                        .setTitle("删除")
                        .setMessage("确定要删除图片吗？")
                        .setNegativeButton("确定") { dialog, _ ->
                            dialog.dismiss()
                            multiImageView.deleteItem(position)
                            mapImageId.remove(position)
                        }
                        .show()
                }
            }
            // 图片加载
            .setImageViewLoader { _, path, imageView ->
                // （这里自己选择图片加载框架，不做限制）
                imageView.setImageURI(Uri.parse("file://$path"))
            }
            // 新增按钮点击回调
            .setAddClickListener {
                selectEvaluateImage()
//                requestPermission()
            }
            .show()
    }

    private fun requestPermission() {
        XXPermissions.with(this)
            .permission(Permission.READ_MEDIA_IMAGES)
            .permission(Permission.READ_MEDIA_VIDEO)
            .permission(Permission.READ_MEDIA_AUDIO)
            .permission(Permission.WRITE_EXTERNAL_STORAGE)
            .interceptor(PermissionInterceptor())
            .request { _, allGranted ->
                if (allGranted) {
                    selectEvaluateImage()
                } else {
                    RxToast.showToast("权限不足，请手动开启权限后重试")
                }
            }
    }

    private fun selectEvaluateImage() {
        val selectionModel: PictureSelectionModel = PictureSelector.create(context)
            .openGallery(SelectMimeType.ofImage())
            .setSelectorUIStyle(PictureSelectorStyle())
            .setImageEngine(GlideEngine.createGlideEngine())
            .setSelectionMode(SelectModeConfig.SINGLE)
            .setCameraInterceptListener(PictureUtil.getCustomCameraEvent())
            .setCompressEngine(PictureUtil.getCompressFileEngine())
            .setPermissionDescriptionListener(PictureUtil.getPermissionDescriptionListener())
            .setPreviewInterceptListener(PictureUtil.getPreviewInterceptListener())
            .setPermissionDeniedListener(PictureUtil.getPermissionDeniedListener())
            .isLoopAutoVideoPlay(false)
            .isPageSyncAlbumCount(true)
            .setLanguage(LanguageConfig.SYSTEM_LANGUAGE)
            .setQuerySortOrder("")
            .isDisplayCamera(true)
            .isOpenClickSound(true)
            .isPreviewImage(false)
            .isMaxSelectEnabledMask(false)
            .isDirectReturnSingle(false)
            .setMaxSelectNum(1)
            .isDirectReturnSingle(true)
        selectionModel.forResult(object : OnResultCallbackListener<LocalMedia> {
            override fun onResult(result: java.util.ArrayList<LocalMedia>?) {
                mRealPath = result!![0].realPath
                /** 方案1：不压缩图片，直接上传 */
//                val imageFile = File(mRealPath)
                /** 方案2：压缩图片后上传 */
//                val bitmap = BitmapFactory.decodeFile(mRealPath)
//                val bitmapCompress = ImgUtils.compressByQuality(bitmap, 500)
//                val fileCompress = ImgUtils.saveBitmapFile(bitmapCompress)
//                showLoading(getString(R.string.loading))
//                mViewModel.uploadFile(fileCompress)
                // 把单张图片压缩到1024k以内 同时像素不超过1200（宽、高都不大于1200）
                EasyImgCompress.withSinglePic(context, result[0].realPath)
                    .maxPx(1200)
                    .maxSize(1024)
                    .enableLog(true)
                    .setOnCompressSinglePicListener(object : OnCompressSinglePicListener {
                        override fun onStart() {
                            LogUtils.debugInfo("onStart")
                        }

                        override fun onSuccess(file: File) {
                            showLoading(getString(R.string.loading))
                            mViewModel.uploadFile(file)
                            LogUtils.debugInfo("onSuccess size = " + GBMBKBUtil.getSize(file.length()) + " getAbsolutePath= " + file.absolutePath)
                        }

                        override fun onError(error: String) {
                            LogUtils.debugInfo("onError error = $error")
                        }
                    }).start()
            }

            override fun onCancel() {}
        })
    }

    private fun addNewData(realPath: String?) {
        val tempList: MutableList<ImageModel> = ArrayList()
        val model = ImageModel()
        model.path = realPath
        tempList.add(model)
        /** 调用新增数据 */
        mDatabind.uploadMultiImageView.addNewData(tempList.toList())
    }
}